package com.caird.pmp.iot.handler.impl;

import com.alibaba.fastjson.JSONObject;
import com.caird.pmp.iot.entity.ProduceDeviceResult;
import com.caird.pmp.iot.handler.HandlerBase;
import com.caird.pmp.iot.message.IMessage;
import com.caird.pmp.iot.message.MessageFactory;
import com.caird.pmp.iot.message.impl.DeviceMessage01E0;
import com.caird.pmp.iot.message.impl.ServerMessage81E0;
import com.caird.pmp.iot.server.BbChannelManager;
import com.caird.pmp.iot.service.IIotService;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

@Slf4j
@Controller
public class Handler01E0 extends HandlerBase {

    @Resource
    private IIotService iotService;

    @Override
    public boolean handle(Channel channel, IMessage message) {
        DeviceMessage01E0 dm = (DeviceMessage01E0)message;

        ServerMessage81E0 sm = (ServerMessage81E0) MessageFactory.make("81E0");
        sm.setSimNo(dm.getSimNo());
        sm.setFlowNo(BbChannelManager.getFlowNo(channel));

        //生产设备
        JSONObject response = iotService.produceDevice(dm.getBatchCode(), dm.getMcuId(), dm.getIccid(), dm.getReport());
        if (response.getBoolean("success")) {
            ProduceDeviceResult produceDeviceResult = response.getObject("result", ProduceDeviceResult.class);
            sm.setResult(produceDeviceResult.getResult());
            sm.setLicense(produceDeviceResult.getLicense());
            sm.setSn(produceDeviceResult.getSn());
            sm.setFullSimNo(produceDeviceResult.getSimNo());
            sm.setVin(produceDeviceResult.getVin());
            writeAndFlush(channel, sm.encode());
        }

        return true;
    }
}
